#pragma once

#include "timerManager.hpp"
#include "usersManager..hpp"
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <assert.h>
#include <sys/epoll.h>
#include <signal.h>
#include <unistd.h>


#define MAX_EVENT_NUM 1024
#define TIMESLOT 5
class server
{
public:
    server(short port)
        :_port(port),_epollfd(epoll_create(5))
    {
        _listenfd = socket(AF_INET,SOCK_STREAM,0);
        assert(_listenfd != -1);
        
        addfd(_epollfd,_listenfd);

        int val = 1;
        setsockopt(_listenfd,SOL_SOCKET,SO_REUSEADDR,&val,1);

        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr("0.0.0.0");
        int n = bind(_listenfd,(const sockaddr *)&server,sizeof(server));
        assert(n != -1);

        n = listen(_listenfd,5);
        assert(n != -1);

        addsig(SIGALRM);// 添加一个超时信号
        alarm(TIMESLOT);// 设置SIGALRM信号产生的频率   
    }

    void start()
    {
        while(true)
        {
            int ret = epoll_wait(_epollfd,_events,MAX_EVENT_NUM,-1);
            if(ret < 0 && errno != EINTR)
            {
                std::cout << "epoll_wait出错!" << std::endl;
                break;
            }
            for(int i=0;i<ret;i++)
            {
                int sockfd = _events[i].data.fd;
                if(sockfd == _listenfd)
                {
                    struct sockaddr_in client;
                    socklen_t len = sizeof(client);
                    int connfd = accept(sockfd,(sockaddr *)&client,&len);
                    assert(connfd != -1);
                    addfd(_epollfd,connfd);// 关键

                    timer *tm = new timer;
                    tm->set_expire(time(nullptr) + 3 * TIMESLOT);
                    tm->set_expire_handler(timer_callback);
                    _tm.add(tm);

                    _um.create_user(connfd,client,tm);
                    std::cout << "创建了一个用户连接: " << connfd << std::endl;
                }
            }
        }
    }

    void addfd(int epollfd,int fd)
    {
        epoll_event event;
        event.data.fd = fd;
        event.events = EPOLLIN | EPOLLRDHUP;
        int n = epoll_ctl(epollfd,EPOLL_CTL_ADD,fd,&event);
        assert(n != -1);
    }

    static void signal_callback(int sig)
    {

    }

    void addsig(int sig)
    {
        struct sigaction act;
        act.sa_handler = signal_callback;
        act.sa_flags |= SA_RESTART;
        int n = sigaction(sig,&act,nullptr);
        assert(n != -1);
    }

    static void timer_callback()
    {

    }
protected:
    timer_manager _tm;
    user_namager _um;
    int _listenfd;
    short _port;
    epoll_event _events[MAX_EVENT_NUM];
    int _epollfd;
};